# -*- coding: utf-8 -*-

import sys
import os
import requests
import json
import time
import re
import traceback,threading
import MySQLdb
import datetime
from selenium.webdriver.firefox.options import Options

print('>>>正在初始化...')

DataBase = "sccplat"
HTTP_SB_URL = 'http://ydhzcms.bimsheng.com/daping/rest/people/'
proDir = os.path.split(os.path.realpath(__file__))[0]
SQL_CONNEC_URL = 'rm-bp1z598ttm5ahi9o15o.mysql.rds.aliyuncs.com'
SQL_USER_NAME = 'wangjun'
SQL_PWD = 'wj123456'
SQL_PORT = 3306
print('proDir---',proDir)
proDir = proDir.replace('agent','')
import time
from selenium import webdriver
need_borwer_info_list = []

#开心芝麻代理ip
#https://zhimahttp.com/getapi/
#18701726387
#dtld123456
def loginurl(miniters=300,browser=None):
    cookie = None
    

    try:

        global need_borwer_info_list
        need_borwer_info_list = []#清空
        # browser.get('https://www.baidu.com/s?wd=ip')#百度查ip
        browser.get('http://jm.jxxfnet.cn')
        time.sleep(2)
        # #定位到账号的输入框
        # id_input = browser.find_element_by_xpath('//input[@id="j_username"]')
        # time.sleep(2)
        # id_input.send_keys(account)
        # #定位到密码输入框，输入密码
        # pw_input = browser.find_element_by_xpath('//input[@id="j_password"]')
        # pw_input.send_keys(password)
        # time.sleep(1)
        # #点击登录按钮
        # browser.find_element_by_xpath('//button[@class="white loginBt"]').click()
        # time.sleep(2)
        # # #获取登录的cookie
        cookie = browser.get_cookies()
        
        cookiearr = []
        for item in cookie:
            cookiearr.append(item['name']+'='+item['value'])
        cookiestr = ';'.join(cookiearr)
        print('cookiestr---',cookiestr)
    
    except:
        traceback.print_exc()
        print('异常处理')
    
    
    
class MainThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        # config = configparser.ConfigParser()
        
        # configPath = os.path.join(proDir, "config.ini")
        # config.read(configPath)
        # username = config.get('config','username')
        # password = config.get('config','password')
        # miniters = int(config.get('config','miniters'))

        ####linux下开始
        options = webdriver.FirefoxOptions()
        options.add_argument('--headless')
        #linux下结束

        ####window下开始
        #创建一个浏览器对象,windows
        # profile=webdriver.FirefoxProfile()
        # profile.accept_untrusted_certs=True
        # geckodriverPath = os.path.join(proDir, "geckodriver")
        # browser=webdriver.Firefox(firefox_profile=profile,executable_path=geckodriverPath) 
        ####window下结束
        while True:
            try:
                # loginurl(username,password,miniters)
                browser = webdriver.Firefox(firefox_options=options)#linux
                # browser=webdriver.Firefox(firefox_profile=profile,executable_path=geckodriverPath) #windows版
                pwd = selectFDb('sjsso_account',name='18616728227')
                print('pwd---',pwd)
                if pwd:
                    loginurl('18616728227',pwd,60,browser)
                if browser:
                    browser.close()
                    browser = None

                curr_time = datetime.datetime.now()
                print("线程在跑----",curr_time.strftime('%Y-%m-%d %H:%M:%S'))

            except Exception as e:
                print('登录主线程报错，继续执行。。。。')
                traceback.print_exc()
            
            time.sleep(300)


if __name__ == '__main__':
    print(">>>>>>>>  login")
    
    # MainThread().start()
    # print('执行成功')
    # time.sleep(2)

    
    try:
        #搭建自己的ip池文章
        # https://blog.csdn.net/weixin_44517301/article/details/103393145
        browser = None
        profile=webdriver.FirefoxProfile()


        proxy = '59.59.142.178:4210'
        ip, port = proxy.split(":")
        port = int(port)
        # 不使用代理的协议，注释掉对应的选项即可
        settings = {
            'network.proxy.type': 1,  # 0: 不使用代理；1: 手动配置代理
            'network.proxy.http': ip,
            'network.proxy.http_port': port,
            'network.proxy.ssl': ip,  # https的网站,
            'network.proxy.ssl_port': port,
        }

        # 更新配置文件
        for key, value in settings.items():
            profile.set_preference(key, value)
        profile.update_preferences()
        options = Options()

        # proxy = '122.243.8.86:8080' 
        # options = webdriver.ChromeOptions()
        # options.add_argument("–proxy-server=http://" + proxy)
        # options.add_argument('user-agent="%s"' % 'xxxx')

        profile.accept_untrusted_certs=True
        geckodriverPath = os.path.join(proDir, "geckodriver")#将驱动放在同目录下
        browser=webdriver.Firefox(firefox_profile=profile,executable_path=geckodriverPath,options=options) #windows版
        
        loginurl(60,browser)
    except Exception as e:
        print('登录主线程报错，继续执行。。。。')
        traceback.print_exc()

